<?php defined('SYSPATH') OR die('No direct script access.');
/**
 * Redis-based session class.
 *
 */
class Kohana_Session_Redis extends Session {

	// redis instance
	protected $_redis;

	// Garbage collection requests
	protected $_gc = 500;

	// The current session id
	protected $_session_id;

	// The old session id
	protected $_update_id;


	public function __construct(array $config = NULL, $id = NULL)
	{

		// connect redis
        $redis = new Redis();
        $redis->connect($config['host'], $config['port']); //连接Redis
        if($config['password'])
        {
            $redis->auth($config['password']); //密码验证
        }
        $redis->select($config['database']);//选择数据库2
        $this->_redis = $redis;
        $this->_lifetime = $config['lifetime'] ? $config['lifetime'] : 3600;
		parent::__construct($config, $id);

	}

	public function id()
	{
		return $this->_session_id;
	}

	protected function _read($id = NULL)
	{
        //判断当前用户是否有相应session_id
		if ($id OR $id = Cookie::get($this->_name))
		{

		    $result = $this->_redis->get($id);
			if ($result)
			{
				// Set the current session id
				$this->_session_id = $this->_update_id = $id;

				// Return the result
				return $result;
			}
		}

		// Create a new session id
		$this->_regenerate();

		return NULL;
	}

	protected function _regenerate()
	{
		do
		{
			// Create a new session id
			$id = str_replace('.', '-', uniqid(NULL, TRUE));

			// Get the the id from the database
			$result = $this->_redis->exists($id);
		}
		while ($result);

		return $this->_session_id = $id;
	}

	protected function _write()
	{
        $this->_redis->setex($this->_session_id,$this->_lifetime,$this->__toString());

		// The update and the session id are now the same
		$this->_update_id = $this->_session_id;

		// Update the cookie with the new session id
		Cookie::set($this->_name, $this->_session_id, $this->_lifetime);

		return TRUE;
	}

	/**
	 * @return  bool
	 */
	protected function _restart()
	{
		$this->_regenerate();

		return TRUE;
	}

	protected function _destroy()
	{
		if ($this->_update_id === NULL)
		{
			// Session has not been created yet
			return TRUE;
		}
		try
		{
            $this->_redis->del($this->_update_id);
			// Delete the cookie
			Cookie::delete($this->_name);
		}
		catch (Exception $e)
		{
			// An error occurred, the session has not been deleted
			return FALSE;
		}

		return TRUE;
	}

	protected function _gc()
	{

	}

} // End Session_Database
